package com.jackrain.clouddata.oms.mq;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.jackrain.nea.core.db.Tools;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.web.query.QueryEngine;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.util.Date;

/**
 * Created by nathan on 2017/8/23.
 */
public class MonitorLogIntercept implements MethodInterceptor {
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        //执行织入的日志
        if (method.getName().equals("consume")) {
            beforeConsume((Message)objects[0],(ConsumeContext)objects[1]);
        }
        Object rev = methodProxy.invokeSuper(o, objects);
        return rev;
    }

    /**
     * MQ日志
     */
    public void beforeConsume(Message message, ConsumeContext context) {
        String[] tags = message.getTag().split(":");
        String tag = null;
        if(tags.length > 0){
            tag = tags[0];
        }

        String updateSql = "UPDATE ONS_SENDMONITOR SET STATE=1,MODIFIEDDATE=? where MSGKEY=? ";

        String insertSql = "INSERT INTO ONS_SENDMONITOR (ID,AD_CLIENT_ID,PTYPE,TOPICID,TAG,STATE,MSGKEY,MSGID,CONSUMER_ERROR,CREATIONDATE,MODIFIEDDATE)" +
                "values (?,?,?,?,?,?,?,?,?,?,?)";

        int cnt = QueryEngine.getInstance().
                executeUpdate(updateSql,
                        new Object[]{new Timestamp((new Date()).getTime()),message.getKey()});
        if(cnt == 0){
            //查询topicid
            String topicSql = "SELECT ID FROM OMS_TOPIC WHERE ISACTIVE='Y' AND TOPIC=?";
            JSONObject topicJson = QueryEngine.getInstance().doQueryObject(topicSql,new Object[]{message.getTopic()});

            QueryEngine.getInstance().
                    executeUpdate(insertSql,
                            new Object[]{Tools.getSequence("ONS_SENDMONITOR"),0,2,
                                    topicJson.get("ID"), tag, 1,message.getKey(),message.getMsgID(),"N", new Timestamp((new Date()).getTime()),new Timestamp((new Date()).getTime())});

        }
    }


    /**
     * MQ日志
     */
    public void throwConsume(Message message, ConsumeContext context,Exception e) {
//        String[] tags = message.getTag().split(":");
//        String tag = null;
//        if(tags.length > 0){
//            tag = tags[0];
//        }
//        String clientIdSql = "SELECT AD_CLIENT_ID FROM OMS_TAG WHERE ISACTIVE='Y' AND TAGNAME = ?";
//        JSONObject clientJson = QueryEngine.getInstance().doQueryObject(clientIdSql,new Object[]{tag});
//        if (clientJson == null){
//            throw new NDSException("公司ID未找到!");
//        }
//        Long clientId = clientJson.getLong("AD_CLIENT_ID");

        //消费失败
        String updateSql = "UPDATE ONS_SENDMONITOR SET CONSUMER_ERROR='Y',PDESC=concat(PDESC,?),STATE=2 where MSGKEY=?";

        int cnt = QueryEngine.getInstance().
                executeUpdate(updateSql,
                        new Object[]{message.getKey()});
    }



    /**
     * MQ日志
     */
    public void afterConsume(Message message, ConsumeContext context) {

//        String[] tags = message.getTag().split(":");
//        String tag = null;
//        if(tags.length > 0){
//            tag = tags[0];
//        }
//
//        String clientIdSql = "SELECT AD_CLIENT_ID FROM OMS_TAG WHERE ISACTIVE='Y' AND TAGNAME = ?";
//        JSONObject clientJson = QueryEngine.getInstance().doQueryObject(clientIdSql,new Object[]{tag});
//        if (clientJson == null){
//            throw new NDSException("公司ID未找到!");
//        }
//        Long clientId = clientJson.getLong("AD_CLIENT_ID");

        //消费成功
        String updateSql = "UPDATE ONS_SENDMONITOR SET CONSUMER_ERROR='N',STATE=2 where MSGKEY=?";

        int cnt = QueryEngine.getInstance().
                executeUpdate(updateSql,
                        new Object[]{message.getKey()});
    }


}
